import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/punch_in_rule/bean/punch_in_rule_bean.dart';
import 'package:e_reception_flutter/ui/punch_in_rule/bean/set_punch_rule_response.dart';
import 'package:e_reception_flutter/ui/punch_in_rule/event/refresh_rule_list_event.dart';
import 'package:e_reception_flutter/ui/punch_in_rule/set_rule/set_punch_in_rule_page.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import '../punch_in_rule_list_widget.dart';

class SetPunchInRuleViewModel extends BaseViewModel {
  bool isStaff = true;

  ///重复数据
  ValueNotifier<List<RepeatBean>> repeatNotifier;

  ///通用规则编辑结果
  ValueNotifier<bool> editGeneralRuleResult;

  ///自定义规则删除结果
  ValueNotifier<bool> deleteRuleResult;

  SetPunchInRuleViewModel(BaseState<StatefulWidget> state) : super(state) {
    repeatNotifier = ValueNotifier(null);
    editGeneralRuleResult = ValueNotifier(false);
    deleteRuleResult = ValueNotifier(null);
    if (state.widget is SetPunchInRulePage) {
      isStaff = (state.widget as SetPunchInRulePage).type ==
          PunchInRuleListWidget.TYPE_STAFF;
    }
  }

  ///编辑通用规则
  void editGeneralRule(PunchInRuleBean ruleBean) {
    if (ruleBean?.delflg != '01') {
      if(!ruleBean.canCommit()){
        if (StringUtils.isEmpty(ruleBean.onDutyTime)) {
          toast('请设置上班时间、下班时间或者时长要求');
          return;
        }
      }


      loading(true, msg: "正在保存");
    } else {
      loading(true, msg: "正在删除");
    }
    //   type(00部门 01班级)

    Map<String, dynamic> params = {
      'authId': UserRepository.getInstance().authId,
      'companyid': UserRepository.getInstance().getCompanyId(),

      'duration': ruleBean.duration ?? 0,
      //上班时间
      'dutytime': ruleBean.onDutyTime,
      //上班弹性时间 秒
      'onFlextime': ruleBean.onDutyFlexibleTime ?? 0,
      //学员/员工
      'groupType': ruleBean.roleType?? '00',
      //下班弹性时间 秒
      'offFlextime': ruleBean.offDutyFlexibleTime ?? 0,
      //下班时间
      'offdutytime': ruleBean.offDutyTime,
      //规则类型
      'type': ruleBean.type == PunchInRuleType.general ? '00' : '01',
    };
    if (ruleBean.id != null) {
      //编辑
      params["arid"] = ruleBean.id;
    }
    loading(true, msg: '正在保存');
    VgHttpUtils.get(NetApi.Edit_GENERAL_PUNCH_IN_RULE,
        params: params,
        callback: BaseCallback(onSuccess: (val) {
          loading(false);
          BaseResponseBean responseBean = BaseResponseBean.fromMap(val);
          editGeneralRuleResult.value =
              responseBean != null && responseBean.success;
          VgEventBus.global.send(RefreshRuleListEvent('编辑通用规则成功'));
        }, onError: (msg) {
          loading(false);
          editGeneralRuleResult.value = false;
        }));
  }

  ///添加规则
  void addRule(PunchInRuleBean ruleBean) {
    //   type(00部门 01班级)
    if(!ruleBean.canCommit()){
      if (StringUtils.isEmpty(ruleBean.onDutyTime)) {
        toast('请设置上班时间、下班时间或者时长要求');
        return;
      }
    }
    if (ruleBean.type == PunchInRuleType.custom) {
      if (ruleBean.suitableObjectIds == null ||
          ruleBean.suitableObjectIds.length == 0) {
        toast('请选择适用对象');
        return;
      }
    }

    loading(true, msg: "正在保存");
    String chooseIds = ruleBean.suitableObjectIds?.join(',') ?? '';
    Map<String, dynamic> params = {
      'authId': UserRepository.getInstance().authId,
      "chooseIds": chooseIds,
      "cover": (ruleBean.cover ?? false) ? "01" : "00",
      "coverId": ruleBean.coverid ?? '',
      // "BJTime": DateTime.now().millisecondsSinceEpoch.toString(),
      "arid": ruleBean.id,
      'companyid': UserRepository.getInstance().getCompanyId(),
      'departmentid': isStaff ? chooseIds : '',
      "classid": (!isStaff) ? chooseIds : '',
      // 'createDate':'',
      // "createUid":'',
      // "dayRuleid":
      'duration': ruleBean.duration ?? 0,
      //上班时间
      'dutytime': ruleBean.onDutyTime,
      //上班弹性时间 秒
      'onFlextime': ruleBean.onDutyFlexibleTime ?? 0,
      //学员/员工
      'groupType': ruleBean.roleType,
      //下班弹性时间 秒
      'offFlextime': ruleBean.offDutyFlexibleTime ?? 0,
      //下班时间
      'offdutytime': ruleBean.offDutyTime,
      //规则名称
      'ruleName': ruleBean.name,
      //规则类型
      'type': ruleBean.type == PunchInRuleType.general ? '00' : '01',
    };

    HttpUtils.get(
      url: StringUtils.isEmpty(ruleBean.id)?NetApi.ADD_CUSTOMIZE_PUNCH_IN_RULE:NetApi.EDIT_CUSTOMIZE_PUNCH_IN_RULE,
      query: params,
    ).then((value) {
      loading(false);
      if (value != null && value.isSucceed() && value.data != null) {
        SetPunchRuleResponse response =
            SetPunchRuleResponse.fromMap(value.data);
        if (response.success) {
          VgEventBus.global.send(RefreshRuleListEvent('新增个性化规则成功'));
          repeatNotifier.value = [];
        } else {
          if (response.data != null) {
            List<RepeatBean> repeatList = response.data ?? [];
            repeatNotifier.value = repeatList;
          } else {
            toast("" + response.msg);
          }
        }
      } else {
        toast("请求失败${value?.message ?? ''}");
      }
    }).catchError((e) {
      toast(e?.toString());
    });
  }

  ///删除
  void delete(PunchInRuleBean ruleBean) {
    loading(true, msg: '正在删除');

    Map<String, dynamic> params = {
      'authId': UserRepository.getInstance().authId,
      "arid": ruleBean.id ?? '',
      'delflg': '01'
    };
    VgHttpUtils.get(NetApi.DEL_CUSTOMIZE_PUNCH_IN_RULE,
        params: params,
        callback: BaseCallback(onSuccess: (val) {
          loading(false);
          BaseResponseBean responseBean = BaseResponseBean.fromMap(val);
          if (responseBean != null) {
            if (responseBean.success) {
              VgEventBus.global.send(RefreshRuleListEvent('删除个性化规则成功'));
              deleteRuleResult.value = true;
            } else {
              toast(responseBean.msg);
            }
          } else {
            toast('删除失败');
          }
        }, onError: (msg) {
          loading(false);
          toast('$msg');
        }));
  }
}
